#pragma once

#include <iostream>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <stdio.h>
#include<unistd.h>

#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 4096

using namespace std;

key_t get_key()
{
    key_t k = ftok(PATHNAME, PROJ_ID);
    if (k < 0)
        perror("ftok");
    return k;
}

int getshmFunc(key_t k, int flags)
{
    int shm_id = shmget(k, MAX_SIZE, flags);
    if (shm_id < 0)
        perror("shmget");
    return shm_id;
}

int get_shmid(key_t k)
{
    return getshmFunc(k, IPC_CREAT);
}

int creat_shmid(key_t k)
{
    return getshmFunc(k,IPC_CREAT | IPC_EXCL | 0600);
}



void *attach_shm(int shm_id)
{
    void *mem_ad = shmat(shm_id, NULL, 0);
    if ((long long)mem_ad == -1L)
        perror("shmat");
    return mem_ad;
}

void *detach_shm(void *mem_ad)
{
    if (shmdt(mem_ad) == -1)
        perror("shmdt");
}

void *del_shm(int shm_id)
{
    if (shmctl(shm_id, IPC_RMID, NULL) == -1)
        perror("shmctl");
}